from info.models import Mail, MailReceive
from department.models import Work
from project.models import Participate


def mail_view(mail):
    assert isinstance(mail, Mail)
    view = {
        'id': mail.id,
        'title': mail.title,
        'date_time': {
            'year': mail.date_time.year,
            'month': mail.date_time.month,
            'day': mail.date_time.day,
            'hour': mail.date_time.hour,
            'minute': mail.date_time.minute,
            'second': mail.date_time.second
        },
        'content': mail.content,
        'recipients': [{
            'id': receive.uid.id,
            'name': receive.uid.name
        } for receive in MailReceive.objects.filter(mid=mail)]
    }
    if mail.did is not None:  # 部门邮件
        work = Work.objects.get(uid=mail.uid, rid__did=mail.did)
        view['department'] = {
            'id': mail.did.id,
            'name': mail.did.name,
            'sender': {
                'id': mail.uid.id,
                'name': mail.uid.name,
                'role': {
                    'id': work.rid.id,
                    'name': work.rid.name
                }
            }
        }
    elif mail.pid is not None:  # 项目邮件
        participate = Participate.objects.get(uid=mail.uid, rid__pid=mail.pid)
        view['project'] = {
            'id': mail.pid.id,
            'name': mail.pid.name,
            'sender': {
                'id': mail.uid.id,
                'name': mail.uid.name,
                'role': {
                    'id': participate.rid.id,
                    'name': participate.rid.name
                }
            }
        }
    else:  # 系统邮件
        view['system'] = {
            'sender': {
                'id': mail.uid.id,
                'name': mail.uid.name,
                'role': {
                    'id': mail.uid.rid.id,
                    'name': mail.uid.rid.name
                }
            }
        }
    return view


def mail_list_view(mail_query_set):
    return [{
        'id': mail.id,
        'title': mail.title,
        'sender': {
            'id': mail.uid.id,
            'name': mail.uid.name
        },
        'date_time': {
            'year': mail.date_time.year,
            'month': mail.date_time.month,
            'day': mail.date_time.day,
            'hour': mail.date_time.hour,
            'minute': mail.date_time.minute,
            'second': mail.date_time.second
        }
    } for mail in mail_query_set]
